//
//  TextReaderController.m
//  ChangJiangPress
//
//  Created by 泉 汉水 on 11-12-21.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "TextReaderController.h"
#import "CommonUtil.h"
#import "BookConstants.h"
//#import "TableCell2.h"
#import "TableCell2.h"
#define LIMIT_PAGES 20

@implementation TextReaderController
@synthesize bookId, bookFileName;
@synthesize categoryBackground;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        m_bIsShowTool = YES;
        fontSize = 17;
        txtContainerRect = CGRectMake(30, 50, 260, 380);
        //txtContainerRect = CGRectMake(85, 112, 592, 800);
    }
    return self;
}

- (void)dealloc
{
    [mainToolbarView release];
    [bookFileName release];
    [bookId release];
    
    [categoryView release];
    [categoryBackground release];
    [bookCoverView release];
    [bookInfoView release];
    
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //增加扩展按钮和试图
    [self addExtendView];
    
    [self performSelector:@selector(hiddenToolBar) withObject:nil afterDelay:5.0f];
}


-(void)hiddenToolBar {
    [UIView beginAnimations:@"View Curl" context:nil];
    
    if (m_bIsShowTool) {
        [pageSliderView setHidden:YES];
        [mainToolbarView setHidden:YES];
        /*
         CGRect frame = pageSliderView.frame;
         frame.origin.y += frame.size.height; 
         pageSliderView.frame = frame;
         
         frame = mainToolbarView.frame;
         frame.origin.y -= frame.size.height; 
         mainToolbarView.frame = frame;*/
    }
    else 
    {
        [pageSliderView setHidden:NO];
        [mainToolbarView setHidden:NO];
        /*
         CGRect frame = mainToolbarView.frame;
         frame.origin.y -= frame.size.height; 
         mainToolbarView.frame = frame;
         
         frame = pageSliderView.frame;
         frame.origin.y += frame.size.height; 
         pageSliderView.frame = frame;*/
    }
    m_bIsShowTool = !m_bIsShowTool;
    
    UIViewAnimationTransition transition;
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    transition = UIViewAnimationTransitionNone;
    [UIView setAnimationTransition:transition forView:self.view cache:YES];
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}

- (void) addExtendView {    
    
    self.view.autoresizesSubviews = YES;
    
    //中间的按钮
    UIButton *centerButton = [[UIButton alloc] initWithFrame:CGRectMake(50, 60, 220, 340)];
    //centerButton.backgroundColor = [UIColor redColor];
    centerButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
    [centerButton addTarget:self action:@selector(centerClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:centerButton];
    [centerButton release];
    
    //上方工具栏
    mainToolbarView = [[UIView alloc] initWithFrame:CGRectMake(10, 7, 300, 30)];
    mainToolbarView.backgroundColor = [UIColor clearColor];
    //关闭按钮
    UIButton *closeButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 0, 70, 35)];
    [closeButton addTarget:self action:@selector(closeClick:) forControlEvents:UIControlEventTouchUpInside];
    [closeButton setImage:[UIImage imageNamed:@"text_library_2.png"] forState:UIControlStateNormal];
    [mainToolbarView addSubview:closeButton];
    [closeButton release];
    //目录按钮
    UIButton *categoryButton = [[UIButton alloc] initWithFrame:CGRectMake(77, 0, 46, 35)];
    [categoryButton addTarget:self action:@selector(categoryClick:) forControlEvents:UIControlEventTouchUpInside];
    [categoryButton setImage:[UIImage imageNamed:@"text_list.png"] forState:UIControlStateNormal];
    [mainToolbarView addSubview:categoryButton];
    [categoryButton release];
    
    //字体缩小按钮
    fontMinusButton = [[UIButton alloc] initWithFrame:CGRectMake(180, 0, 35, 35)];
    fontMinusButton.tag = 1;
    [fontMinusButton addTarget:self action:@selector(fontChangeClick:) forControlEvents:UIControlEventTouchUpInside];
    [fontMinusButton setImage:[UIImage imageNamed:@"text_font_minus.png"] forState:UIControlStateNormal];
    [mainToolbarView addSubview:fontMinusButton];
    //字体放大按钮
    fontPlusButton = [[UIButton alloc] initWithFrame:CGRectMake(215, 0, 35, 35)];
    fontPlusButton.tag = 2;
    [fontPlusButton addTarget:self action:@selector(fontChangeClick:) forControlEvents:UIControlEventTouchUpInside];
    [fontPlusButton setImage:[UIImage imageNamed:@"text_font_plus.png"] forState:UIControlStateNormal];
    [mainToolbarView addSubview:fontPlusButton];
    [self.view addSubview:mainToolbarView];
    //书签
    bookmarkButton = [[UIButton alloc] initWithFrame:CGRectMake(250, -6, 48, 48)];
    bookmarkButton.tag = 1;
    [bookmarkButton addTarget:self action:@selector(bookmarkClick:) forControlEvents:UIControlEventTouchUpInside];
    [bookmarkButton setImage:[UIImage imageNamed:@"text_mark.png"] forState:UIControlStateNormal];
    [mainToolbarView addSubview:bookmarkButton];
    [self.view addSubview:mainToolbarView];
    
    //下方页码滚动轴
    pageSliderView = [[UIView alloc] initWithFrame:CGRectMake(30, 420, 260, 30)];
    //pageSliderView.backgroundColor = [UIColor redColor];
    //categoryBackground = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"text_bg_2.png"]];
    //[categoryView addSubview:categoryBackground];
    pageSlider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, 260, 20)];
    [pageSlider addTarget:self action:@selector(gotoPageClick:) forControlEvents:UIControlEventTouchUpInside];
    [pageSliderView addSubview:pageSlider];
    [self.view addSubview:pageSliderView];
    
    //目录
    categoryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    categoryBackground = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"text_bg_11.png"]];
    [categoryView addSubview:categoryBackground];
    //[categoryBackground release];
    //关闭（2）
    UIButton *close2Button = [[UIButton alloc] initWithFrame:CGRectMake(15, 7, 70, 35)];
    [close2Button addTarget:self action:@selector(closeClick:) forControlEvents:UIControlEventTouchUpInside];
    [close2Button setImage:[UIImage imageNamed:@"text_library_2.png"] forState:UIControlStateNormal];
    [categoryView addSubview:close2Button];
    [close2Button release];
    //续读
    UIButton *contiuneButton = [[UIButton alloc] initWithFrame:CGRectMake(87, 7, 72, 35)];
    [contiuneButton addTarget:self action:@selector(categoryClick:) forControlEvents:UIControlEventTouchUpInside];
    [contiuneButton setImage:[UIImage imageNamed:@"text_continue.png"] forState:UIControlStateNormal];
    [categoryView addSubview:contiuneButton];
    [contiuneButton release];
    
    columnButton = [[UIButton alloc] initWithFrame:CGRectMake(21, 50, 137, 35)];
    [columnButton setImage:[UIImage imageNamed:@"text_category_focus.png"] forState:UIControlStateNormal];
    [columnButton setTag:1];
    [columnButton addTarget:self action:@selector(categoryAndBookmarkClick:) forControlEvents:UIControlEventTouchUpInside];
    [categoryView addSubview:columnButton];
    bookmarkColumnButton = [[UIButton alloc] initWithFrame:CGRectMake(157, 50, 136, 35)];
    [bookmarkColumnButton setImage:[UIImage imageNamed:@"text_bookmark.png"] forState:UIControlStateNormal];
    [bookmarkColumnButton setTag:2];
    [bookmarkColumnButton addTarget:self action:@selector(categoryAndBookmarkClick:) forControlEvents:UIControlEventTouchUpInside];
    [categoryView addSubview:bookmarkColumnButton];
    
    //目录表格
    categoryTableView  = [[UITableView alloc] initWithFrame:CGRectMake(20, 90, 280, 350)];
    categoryTableView.backgroundColor = [UIColor clearColor];
    categoryTableView.dataSource = self;
    categoryTableView.delegate = self;
    [categoryView addSubview:categoryTableView];
    
    //标签表格
    bookmarkTableView  = [[UITableView alloc] initWithFrame:CGRectMake(20, 90, 280, 350)];
    bookmarkTableView.backgroundColor = [UIColor clearColor];
    bookmarkTableView.dataSource = self;
    bookmarkTableView.delegate = self;
    [categoryView addSubview:bookmarkTableView];
    [bookmarkTableView setHidden:YES];
    
    [categoryView setHidden:YES];
    [self.view addSubview:categoryView];
    
    
    waitingView = [[UIActivityIndicatorView alloc] initWithFrame: CGRectMake(225, 25, 20, 20)];
    waitingView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    waitingView.hidesWhenStopped = TRUE;
    [self.view addSubview:waitingView];
    
    if(pagesArray != nil){
        pageSlider.minimumValue = 1.0;
        pageSlider.maximumValue = ([pagesArray count] - 1) * 1.0;
    }
}

-(void)initExtend {
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
//  NSString *resourcePath = [ [NSBundle mainBundle] resourcePath];
//	NSString *filePath = [resourcePath stringByAppendingPathComponent:@"testxx.txt"];
//	bookString=[[NSString alloc] initWithContentsOfFile:filePath  encoding:enc error:nil];   
    bookString = [[[[NSString alloc] initWithContentsOfFile:bookFileName encoding:enc error:nil] stringByReplacingOccurrencesOfString:@"##" withString:@"\n\n##"] mutableCopy];
    //NSLog(@"file:%@", bookString);
    fontSize = 17;
    [self calculatePageNewThread];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	//return YES;
    //return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    return (interfaceOrientation == UIInterfaceOrientationPortrait 
            || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown);
}


#pragma mark LeavesViewDataSource methods
- (NSUInteger) numberOfPagesInLeavesView:(LeavesView*)leavesView {
    return [pagesArray count];
}

- (void) renderPageAtIndex:(NSUInteger)index inContext:(CGContextRef)ctx {
	CGRect bounds = CGContextGetClipBoundingBox(ctx);
    //CGContex
    leavesView.backgroundColor = [UIColor clearColor];
    //CGContextClearRect(ctx, CGRectMake(0, 0, 1024, 748));
    UIImage *image = [UIImage imageNamed:@"text_bg_11.png"];
    CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
    CGContextDrawImage(ctx, imageRect, [image CGImage]);
    
    UIGraphicsPushContext(ctx);
    CGContextSaveGState(ctx);
    CGContextTranslateCTM(ctx, 0.0f, bounds.size.height);
    CGContextScaleCTM(ctx, 1.0f, -1.0f);
    CGContextSetRGBFillColor(ctx, 0, 0, 0, 1);

    UIFont *font = [UIFont systemFontOfSize:fontSize];
    UIFont *titleFont = [UIFont boldSystemFontOfSize:14];
    
    if(index < [pagesArray count]) {
        NSRange range;
        NSValue *value = [pagesArray objectAtIndex:index];
        [value getValue:&range];
        
        [[[bookString substringWithRange:range] stringByReplacingOccurrencesOfString:@"#" withString:@""] drawInRect:CGRectMake(30, 43, 260, 380) withFont:font lineBreakMode:UILineBreakModeWordWrap];
        [[bookItem bookName] drawInRect:CGRectMake(60, 15, 200, 24) withFont:titleFont lineBreakMode:UILineBreakModeCharacterWrap alignment:UITextAlignmentCenter];
        [[NSString stringWithFormat:@"%d/%d", index+1, [pagesArray count]] drawInRect:CGRectMake(60, 435, 200, 24) withFont:titleFont lineBreakMode:UILineBreakModeCharacterWrap alignment:UITextAlignmentCenter];
        
    }
    
    CGContextRestoreGState(ctx);
    UIGraphicsPopContext();
}

/*
 计算页码：1）首先从数据库中查找，如果没有查找到页码数据，则在新线程中计算页码
 */
-(void) calculatePageNewThread {
    if(pagesArray == nil) {
        pagesArray = [[NSMutableArray alloc] initWithCapacity:20];
    }else{
        [pagesArray removeAllObjects];
    }
    if(categoryArray == nil) {
        categoryArray = [[NSMutableArray alloc] initWithCapacity:20];
    }else{
        [categoryArray removeAllObjects];
    }
    if(bookmarkArray == nil) {
        bookmarkArray = [[NSMutableArray alloc] initWithCapacity:20];
    }else{
        [bookmarkArray removeAllObjects];
    }
    if(bookItem == nil){
        bookItem = [[BookItem alloc] init];
    }
    
    DBUtil *db = [[DBUtil alloc] init];
    [db openDB];
    [db getTxtPages:pagesArray page:bookId orient:@"V" 
           fontSize:[NSString stringWithFormat:@"%d",fontSize]];
    [db getTxtCategory:categoryArray page:bookId];
    [db getBookDetailData:bookItem bookId:bookId];
    [db getTxtBookmark:bookmarkArray page:bookId];
    [db closeDB];
    [db release];
    
    if(bookInfoView == nil){
        [self paintBookInfo];
    }
    
    if([pagesArray count] <= 0){
        backgroundJobLock = 1;
        [NSThread detachNewThreadSelector:@selector(startBackgroundJob) toTarget:self withObject:nil];
    }else{
        [self reloadLeavesData];
    }
    
    [self gotoSmartPage];
}


/*
 在新线程中计算页码，计算到第20页和100页的整数倍更新UI试图
 */
-(void)startBackgroundJob {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    //返回一个数组, 包含每一页的字符串开始点和长度(NSRange)
    if(pagesArray == nil) {
        pagesArray = [[NSMutableArray alloc] initWithCapacity:20];
    }
    if(categoryArray == nil) {
        categoryArray = [[NSMutableArray alloc] initWithCapacity:20];
    }
    
    //断行类型
    //UILineBreakMode lineBreakMode=UILineBreakModeCharacterWrap;
    UILineBreakMode lineBreakMode=UILineBreakModeWordWrap;
    
    //CGRect r = CGRectMake(85, 112, 390, 538);
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    //显示字体的行高
    CGFloat lineHeight=[@"Sample样本" sizeWithFont:font].height;
    //NSInteger maxLine=floor(r.size.height/lineHeight);
    NSInteger maxLine=floor(txtContainerRect.size.height/lineHeight);
    NSInteger totalLines=0;
    //NSLog(@"Max Line Per Page: %d (%.2f/%.2f)",maxLine,r.size.height,lineHeight);
    NSString *lastParaLeft=nil;
    NSRange range=NSMakeRange(0, 0);
    //把字符串按段落分开, 提高解析效率
    NSArray *paragraphs=[bookString componentsSeparatedByString:@"\n"];
    for (int p=0;p< [paragraphs count];p++) {
        NSString *para;
        if (lastParaLeft!=nil) {
            //上一页完成后剩下的内容继续计算            
            para=lastParaLeft;
            lastParaLeft=nil;
        }else {
            para=[paragraphs objectAtIndex:p];
            if([[para stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] hasPrefix:@"#"]){
                //NSLog(@"%d-%@", range.location + range.length, para);
                [categoryArray addObject:[[NSArray alloc] initWithObjects:
                                          [NSString stringWithFormat:@"%d", (range.location + range.length)],//位置
                                          [para stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]],//文字
                                          nil]];
            }
            if (p<[paragraphs count]-1)
                //刚才分段去掉了一个换行,现在换给它
                para=[para stringByAppendingString:@"\n"]; 
        }
        
        /*
         CGSize paraSize=[para sizeWithFont:font
         constrainedToSize:r.size
         lineBreakMode:lineBreakMode];*/
        [self performSelectorOnMainThread:@selector(getTextWidth:) withObject:para waitUntilDone:YES];
        CGSize paraSize = paraSizeGlobal;
        
        NSInteger paraLines=floor(paraSize.height/lineHeight);
        if (totalLines+paraLines<maxLine) {
            totalLines+=paraLines;
            range.length+=[para length];
            if (p==[paragraphs count]-1) {
                //到了文章的结尾 这一页也算
                //[ranges addObject:[NSValue valueWithRange:range]];
                [pagesArray addObject:[NSValue valueWithRange:range]];
                if([pagesArray count] == 10 || ([pagesArray count]) % 100 == 0) {
                    [self performSelectorOnMainThread:@selector(reloadLeavesData) withObject:nil waitUntilDone:NO];
                }
            }
        }else if (totalLines+paraLines==maxLine) {
            //很幸运, 刚好一段结束,本页也结束, 有这个判断会提高一定的效率
            range.length+=[para length];
            //[ranges addObject:[NSValue valueWithRange:range]];
            [pagesArray addObject:[NSValue valueWithRange:range]];
            if([pagesArray count] == 10 || ([pagesArray count]) % 100 == 0) {
                [self performSelectorOnMainThread:@selector(reloadLeavesData) withObject:nil waitUntilDone:NO];
            }
            range.location+=range.length;
            range.length=0;
            totalLines=0;
        }else{
            //重头戏, 页结束时候本段文字还有剩余
            NSInteger lineLeft=maxLine-totalLines;
            CGSize tmpSize;
            NSInteger i;
            BOOL nextPageDotStart = FALSE;
            for (i=1; i<[para length]; i++) {
                //逐字判断是否达到了本页最大容量
                NSString *tmp=[para substringToIndex:i];                
                /*
                 tmpSize=[tmp sizeWithFont:font constrainedToSize:r.size
                 lineBreakMode:lineBreakMode];
                 */
                
                [self performSelectorOnMainThread:@selector(getTextWidth:) withObject:tmp waitUntilDone:YES];
                tmpSize = paraSizeGlobal;
                
                int nowLine=floor(tmpSize.height/lineHeight);
                if (lineLeft<nowLine) {
                    //超出容量,跳出, 字符要回退一个, 应为当前字符已经超出范围了
                    //lastParaLeft=[para substringFromIndex:i-1];
                    NSRange dotRange = [@",.?!\":;，。？！“”、：；‘’…—《》〈〉）" rangeOfString:[tmp substringWithRange:NSMakeRange(i - 1, 1)]];
                    if(dotRange.location != NSNotFound) {
                        nextPageDotStart = TRUE;
                        lastParaLeft=[para substringFromIndex:i-2];
                    }else{
                        lastParaLeft=[para substringFromIndex:i-1];
                    }
                    break;
                }
            }
            
            range.length+=i-1;
            if(nextPageDotStart){
                range.length = range.length - 1;
            }
            //[ranges addObject:[NSValue valueWithRange:range]];
            [pagesArray addObject:[NSValue valueWithRange:range]];
            if([pagesArray count] == 10 || ([pagesArray count]) % 100 == 0) {
                [self performSelectorOnMainThread:@selector(reloadLeavesData) withObject:nil waitUntilDone:NO];
            }
            range.location+=range.length;
            range.length=0;
            totalLines=0;
            p--;
        }
        
    }
    //[self reloadLeavesData];
	[self performSelectorOnMainThread:@selector(saveData2DB) withObject:nil waitUntilDone:NO];
	[self performSelectorOnMainThread:@selector(reloadLeavesData) withObject:nil waitUntilDone:NO];
    [pool release];
}

/*
 重载分页数据和目录数据
 */
-(void)reloadLeavesData {
    //NSLog(@"reloadLeavesData:%d", [pagesArray count]);
    [leavesView reloadDataSlient];
    [categoryTableView reloadData];
    pageSlider.minimumValue = 1.0;
    pageSlider.maximumValue = ([pagesArray count] - 1) * 1.0;
}

-(void)saveData2DB {
    DBUtil *db = [[DBUtil alloc] init];
    [db openDB];
    [db setTxtPages:pagesArray page:bookId orient:@"V" 
           fontSize:[NSString stringWithFormat:@"%d",fontSize]];
    [db setTxtCategory:categoryArray page:bookId orient:@"C"];
    [db closeDB];
    [db release];
    backgroundJobLock = 0;
}

-(void) centerClick:(id)sender {
    if(mainToolbarView.hidden){
        [mainToolbarView setHidden:NO];
        [pageSliderView setHidden:NO];
    }else{
        [mainToolbarView setHidden:YES];
        [pageSliderView setHidden:YES];
    }
}

-(void) closeClick:(id)sender {
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(tableView == categoryTableView) {
        return [categoryArray count];
    }else{
        return [bookmarkArray count];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == categoryTableView) {
        static NSString *CellTableIdentifier = @"SimpleCellTableIdentifier ";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                                 CellTableIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
                                           reuseIdentifier: CellTableIdentifier] autorelease];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        
        cell.textLabel.font = [UIFont systemFontOfSize:17];
        NSArray *a = [categoryArray objectAtIndex:[indexPath row]];
        cell.textLabel.text = [[a objectAtIndex:1] stringByReplacingOccurrencesOfString:@"#" withString:@" "];
        for(int i = 0; i < [pagesArray count]; i++) {
            NSRange range;
            NSValue *value = [pagesArray objectAtIndex:i];
            [value getValue:&range];
            if([[a objectAtIndex:0] intValue] >= range.location) {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", (i+1)];
            }/*else if([[a objectAtIndex:0] intValue] == range.location) {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", (i+1)];
            }*/
        }
        //cell.detailTextLabel.text = [a objectAtIndex:0];
        return cell;
    }else if(tableView == bookmarkTableView) {
        static NSString *CellTableIdentifier = @"CellTableIdentifier1";
        TableCell2 *cell = (TableCell2 *)[tableView dequeueReusableCellWithIdentifier:
                                          CellTableIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"TableCell2" owner:self options:nil] objectAtIndex:0];
        }
        NSArray *a = [bookmarkArray objectAtIndex:[indexPath row]];
        cell.title.text = [[[a objectAtIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        for(int i = 0; i < [pagesArray count]; i++) {
            NSRange range;
            NSValue *value = [pagesArray objectAtIndex:i];
            [value getValue:&range];
            if([[a objectAtIndex:0] intValue] >= range.location) {
                cell.page.text = [NSString stringWithFormat:@"%d", (i+1)];
            }
        }
        
        return cell;
    }else {
        return nil;
    }
}

 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
     if(tableView == bookmarkTableView){
         return 45;
     }else{
         return 38;
     }
 }
 /*
 -(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
 return indexPath;
 }
 */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{	
    if(tableView == categoryTableView) { 
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        int page = 1;
        if(cell.detailTextLabel.text != nil && ![cell.detailTextLabel.text isEqualToString:@""]){
            page = [cell.detailTextLabel.text intValue];
        }
        [categoryView setHidden:YES];
        [leavesView didTurnPageAny:(page - 1)];
    }else{
        //bookmark
//        NSLog(@"bookmark1:%d=%d", [bookmarkArray count], [indexPath row]);
//        NSRange range;
//        NSValue *value = [bookmarkArray objectAtIndex:[indexPath row]];
//        [value getValue:&range];
//        NSLog(@"bookmark2:%d=%d", [bookmarkArray count], [indexPath row]);
        NSArray *a = [bookmarkArray objectAtIndex:[indexPath row]];
        for(int i = 0; i < [pagesArray count]; i++) {
            NSRange range2;
            NSValue *value2 = [pagesArray objectAtIndex:i];
            [value2 getValue:&range2];
            if([[a objectAtIndex:0] intValue] < (range2.location + range2.length)) {
                [categoryView setHidden:YES];
                [leavesView didTurnPageAny:i];
                break;
            }
        }
    }
}


-(IBAction) categoryClick:(id)sender {
    if(categoryView.hidden){
        [categoryView setHidden:NO];
    }else{
        [categoryView setHidden:YES];
    }
}


-(IBAction) gotoPageClick:(id)sender {
    UISlider *slider = (UISlider *)sender;
    //NSLog(@"gotoPage:%d", (int)slider.value);
    [leavesView didTurnPageAny:(int)slider.value];
}

-(IBAction) fontChangeClick:(id)sender {
    UIButton *button = (UIButton *)sender;
    int min = 12;
    int max = 24;
    int newFontSize = fontSize;
    if(button.tag == 1) {
        if((fontSize - 3) >= min) {
            newFontSize -= 3;
        }
    }else if(button.tag == 2) {
        if((fontSize + 3) <= max) {
            newFontSize += 3;
        }
    }
    
    
    if(newFontSize != fontSize) {
        currentPage4HV = leavesView.currentPageIndex;// - 1;
        
        if(currentPage4HV < 0) {
            currentPage4HV = 0;
        }
        
        NSValue *value = [pagesArray objectAtIndex:currentPage4HV];
        [value getValue:&currentRange];
        
        fontSize = newFontSize;
        [self calculatePageNewThread];
    }
}

-(void)paintBookInfo {
    bookInfoView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 312, 548)];
    bookInfoView.backgroundColor = [UIColor clearColor];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 312, 80)];
    titleLabel.numberOfLines = 0;
    titleLabel.textAlignment = UITextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:28];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.text = [bookItem bookName];
    [bookInfoView addSubview:titleLabel];
    [titleLabel release];
    
    UILabel *titleLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 80, 312, 30)];
    titleLabel2.numberOfLines = 0;
    titleLabel2.textAlignment = UITextAlignmentCenter;
    titleLabel2.font = [UIFont systemFontOfSize:16];
    titleLabel2.backgroundColor = [UIColor clearColor];
    titleLabel2.textColor = [UIColor blackColor];
    titleLabel2.text = [bookItem bookAuthor];
    [bookInfoView addSubview:titleLabel2];
    [titleLabel2 release];
    
    bookCoverView = [[UIImageView alloc] initWithFrame:CGRectMake(36, 180, 240, 320)];
    //如果图片在本地，则直接显示，否则从服务端下载图片再显示
    if([[NSFileManager defaultManager] fileExistsAtPath:[kDocumentFolder stringByAppendingPathComponent:[bookItem bookIconSmall]]]
       ){
        bookCoverView.image = [UIImage imageWithContentsOfFile:[kDocumentFolder stringByAppendingPathComponent:[bookItem bookIconSmall]]];
    }
    //如果有网络的情况下，下载大图片
    if([CommonUtil isConnected]){
        NSOperationQueue *queue = [NSOperationQueue new];
        [queue setMaxConcurrentOperationCount:1];
        NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
                                            initWithTarget:self
                                            selector:@selector(loadImage:) 
                                            object:[NSString stringWithFormat:@"%@%@%@", kServerURL, kFilei240, [bookItem bookIconSmall]]];
        [queue addOperation:operation]; 
        [operation release];
    }
    
    [bookInfoView addSubview:bookCoverView];
    
    [categoryView addSubview:bookInfoView];
}

-(void)loadImage:(NSString *)url {
    NSData* imageData = [[NSData alloc]initWithContentsOfURL:
                         [NSURL URLWithString:url]];
    bookCoverView.image = [[UIImage alloc] initWithData:imageData];
    [imageData release];
}


-(IBAction) bookmarkClick:(id)sender {
    UIButton *b = (UIButton *)sender;
    
    int current = leavesView.currentPageIndex;// - 1;
    
    if(current < 0) {
        current = 0;
    }
    
    NSRange currentR;
    NSValue *value = [pagesArray objectAtIndex:current];
    [value getValue:&currentR];
    
    if(b.tag == 1) {
        currentR.length = 64;
        DBUtil *db = [[DBUtil alloc] init];
        [db openDB];
        [db addTxtBookmark:bookId location:currentR.location title:[bookString substringWithRange:currentR]];
        [db closeDB];
        [db release];
        
        [bookmarkButton setImage:[UIImage imageNamed:@"bookmark_red_48.png"] forState:UIControlStateNormal];
        [bookmarkButton setTag:2];
    }else if(b.tag == 2) {
        //NSLog(@"delete：%d,%d", currentR.location, currentR.length);
        DBUtil *db = [[DBUtil alloc] init];
        [db openDB];
        [db deleteTxtBookmark:bookId location:currentR.location length:currentR.length];
        [db closeDB];
        [db release];
        
        [bookmarkButton setImage:[UIImage imageNamed:@"text_mark.png"] forState:UIControlStateNormal];
        [bookmarkButton setTag:1];
    }
    
    if(bookmarkArray == nil){
        bookmarkArray = [[NSMutableArray alloc] initWithCapacity:20];
    }else{
        [bookmarkArray removeAllObjects];
    }
    
    DBUtil *db = [[DBUtil alloc] init];
    [db openDB];
    [db getTxtBookmark:bookmarkArray page:bookId];
    [db closeDB];
    [db release];
    [bookmarkTableView reloadData];
}


-(IBAction) categoryAndBookmarkClick:(id)sender {
    UIButton *b = (UIButton *)sender;
    if(b.tag == 1) {
        [columnButton setImage:[UIImage imageNamed:@"text_category_focus.png"] forState:UIControlStateNormal];
        [bookmarkColumnButton setImage:[UIImage imageNamed:@"text_bookmark.png"] forState:UIControlStateNormal];
        [categoryTableView setHidden:NO];
        [bookmarkTableView setHidden:YES];
    }else{
        [columnButton setImage:[UIImage imageNamed:@"text_category_focus.png"] forState:UIControlStateNormal];
        [bookmarkColumnButton setImage:[UIImage imageNamed:@"text_bookmark.png"] forState:UIControlStateNormal];
        
        if(bookmarkArray == nil){
            bookmarkArray = [[NSMutableArray alloc] initWithCapacity:20];
        }else{
            [bookmarkArray removeAllObjects];
        }
        
        DBUtil *db = [[DBUtil alloc] init];
        [db openDB];
        [db getTxtBookmark:bookmarkArray page:bookId];
        [db closeDB];
        [db release];
        
        [bookmarkTableView reloadData];
        
        [categoryTableView setHidden:YES];
        [bookmarkTableView setHidden:NO];
    }
}

- (void) leavesView:(LeavesView *)leavesView didTurnToPageAtIndex:(NSUInteger)pageIndex {
    
    pageSlider.value = (pageIndex + 1) * 1.0;
    
    int current = pageIndex;
    
    if(current < 0) {
        current = 0;
    }
    NSRange range;
    NSValue *value = [pagesArray objectAtIndex:current];
    [value getValue:&range];
    
    [bookmarkButton setImage:[UIImage imageNamed:@"text_mark.png"] forState:UIControlStateNormal];
    [bookmarkButton setTag:1];
    if(bookmarkArray != nil) {
        for(int m=0;m<[bookmarkArray count]; m++){
            int location = [[[bookmarkArray objectAtIndex:m] objectAtIndex:0] intValue];
            if(location >= range.location && location < (range.location + range.length)) {
                [bookmarkButton setImage:[UIImage imageNamed:@"bookmark_red_48.png"] forState:UIControlStateNormal];
                [bookmarkButton setTag:2];
                break;
            }
        }
    }
}

-(void)getTextWidth:(NSString *)string {
    paraSizeGlobal = [string sizeWithFont:[UIFont systemFontOfSize:fontSize] 
                        constrainedToSize:txtContainerRect.size
                            lineBreakMode:UILineBreakModeWordWrap];
}

-(void)gotoSmartPage {
    for(int i = 0; i < [pagesArray count]; i++) {
        NSRange range;
        NSValue *value = [pagesArray objectAtIndex:i];
        [value getValue:&range];
        if(currentRange.location <= (range.location + range.length)) {
            [leavesView didTurnPageAny:i];
            break;
        }
    }
}
@end
